package com.lu.utils;

import cn.hutool.extra.spring.SpringUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.lu.mapper.SysStoreMapper;
import com.lu.model.entity.SysMerchant;
import com.lu.model.entity.SysStore;
import com.lu.model.entity.SysUser;
import com.lu.model.enums.SysUserTypeEnum;
import com.lu.model.exception.LuBootAssert;
import org.springframework.security.core.context.SecurityContextHolder;

import java.util.List;
import java.util.stream.Collectors;

/**
 * Spring Security 工具类
 *
 * @author huangyao
 * @Date: 2022/5/10
 */
public class SecurityUtil {

  private SecurityUtil() {
  }

  /**
   * 获取当前用户
   *
   * @return 用户ID
   */
  public static SysUser getCurrentUser() {
    return (SysUser) SecurityContextHolder.getContext().getAuthentication().getPrincipal();
  }

  /**
   * 是系统用户
   * @return
   */
  public static boolean isSystemUser(){
    return SecurityUtil.getCurrentUser().getUserType() == SysUserTypeEnum.SYS_USER.getType();
  }

  /**
   * 是商户用户
   * @return
   */
  public static boolean isMerchantUser(){
    return SecurityUtil.getCurrentUser().getUserType() == SysUserTypeEnum.SYS_MERCHANT_USER.getType();
  }

  /**
   * 是门店用户
   * @return
   */
  public static boolean isStoreUser(){
    return SecurityUtil.getCurrentUser().getUserType() == SysUserTypeEnum.SYS_STORE_USER.getType();
  }

  public static SysMerchant getMerchant(){
    SysMerchant merchant = SecurityUtil.getCurrentUser().getMerchant();
    LuBootAssert.isTrue(merchant != null, "当前登录不是商户用户账号");
    return merchant;
  }

  public static SysStore getStore(){
    SysStore store = SecurityUtil.getCurrentUser().getStore();
    LuBootAssert.isTrue(store != null, "当前登录不是门店用户账号");
    return store;
  }

  public static List<Long> getMerchantStoreIds(){
    SysMerchant merchant = getMerchant();
    QueryWrapper<SysStore> sysStoreQueryWrapper = new QueryWrapper<>();
    sysStoreQueryWrapper.select("id");
    sysStoreQueryWrapper.eq("relation_id", merchant.getId());
    sysStoreQueryWrapper.eq("business_mode", SysStore.BusinessMode.OFFLINE.getMode());
    SysStoreMapper sysStoreMapper = SpringUtil.getBean(SysStoreMapper.class);
    List<Long> merchantStoreIds = sysStoreMapper.selectList(sysStoreQueryWrapper).stream().map(SysStore::getId).collect(Collectors.toList());
    return merchantStoreIds;
  }

}
